<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/28
 * Time: 16:28
 */

namespace app\admin\controller\log;


use app\admin\logic\MoneyLogic;
use app\common\controller\Backend;
use app\common\utils\Constant;
use app\common\utils\WeChatRedUtils;
use app\common\utils\WeChatSendRedPackUtils;
use app\common\utils\WeChatSendRedUtils;
use app\index\logic\MessageLogic;
use think\Db;
use think\Exception;

/**
 * 提现记录管理
 * Class Withdrawlog
 * @package app\admin\controller\log
 */
class Withdrawlog extends Backend
{
    protected $model = null;

    public function _initialize(){
        parent::_initialize();
        $this->model = model('Withdrawals');
    }

    /**
     * 查看
     */
    public function index()
    {

        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        if ($this->request->isAjax())
        {
            $map= [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($user['user_type'] == Constant::USER_TYPE_PROPERTY) {
                $map['property_id'] = $user['property_id'];
            }
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>&$value){
                $value['user_nickname'] = model('User')->where(array('id'=>$value['admin_id']))->value('nickname');
                $value['property_name'] = model("Property")->where(array('id'=>$value['property_id']))->value('name');
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig('user_type', $user['user_type']);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $poundage = $this->getConfigByName("poundage");
        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        //过滤非物业人员
        if($user['user_type'] != Constant::USER_TYPE_PROPERTY){
            $this->error("不是物业人员无法操作");
        }
        $property = model("Property")->where(array('id'=>$user['property_id']))->find();
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                //验证字段
                if(!is_numeric($params['money']) || $params['money'] <= 0 || empty($params['money'])){
                    $this->error('金额参数错误');
                }
                if(empty($params['bank_name'])){
                    $this->error("银行名称为空");
                }
                if(empty($params['account_bank'])){
                    $this->error("银行账号为空");
                }
                if(empty($params['account_name'])){
                    $this->error("银行账号名为空");
                }
                if($property['money_over'] < $params['money']){
                    $this->error("余额不足");
                }
                $params['create_time'] = time();
                $params['admin_id'] = $userId;
                $params['property_id'] = $property['id'];
                //计算手续费
                $params['poundage'] = bcmul($params['money'], $poundage, 2);
                $params['money'] = bcsub($params['money'], $poundage, 2);
                try{
                    Db::startTrans();
                    $re = Db::name("withdrawals")->insert($params);
                    if(!$re){
                        Db::rollback();
                        $this->error("提交失败");
                    }
                    Db::name('property')->where("id={$property['id']}")->setInc("money_lock", $params['money']);
                    Db::name('property')->where("id={$property['id']}")->setDec("money_over", $params['money']);
                    Db::commit();
//                    $this->error("1");
                    $this->success("提交成功请等待审核");
                }catch (Exception $e){
                    Db::rollback();
                    return $this->error($e->getMessage());
                }
            }
        }
        $this->assignconfig("poundage", $poundage);
        $this->assignconfig("money", $property['money_over']);
        return $this->view->fetch();
    }


    /**
     * 审核申请记录
     * @param string $ids
     * @return mixed
     */
    public function verify($ids=''){
        if ($this->request->isAjax()) {
            Db::startTrans();
            try {
                $verify_log = $this->model->where(array('id' => $ids))->find();
                if ($verify_log['status'] != Constant::VERIFY_STATUS_WAIT) {
                    $this->error('该记录已经审核过，无法重复审核!');
                }
                $data = $this->request->post("row/a");
                if(!isset($data['status']) || $data['status'] == ''){
                    $this->error('请选择是否通过审核!');
                }
                if($data['status'] == Constant::VERIFY_STATUS_FAIL){
                    //退还余额
                    $change_type = Constant::CHANGE_TYPE_WITHDRAWAL_FAILURE;
                    $money_type = 2; //提现费用
                    $in_out_type = Constant::IN_OUT_TYPE_IN;
                    $money = $verify_log['money'] + $verify_log['poundage'];
                    $desc = '提现失败，资金返回到余额';
                    $map['id'] = $verify_log['property_id'];
                    model('Property')->where($map)->setInc('money_over',$money);
                    model('Property')->where($map)->setDec('money_lock',$money);
                    $property = model('Property')->where($map)->find();
                    $current_money = $property['money_over']+$property['money_lock'];
                    $logic = new MoneyLogic();
                    $logic->saveMoneyLog($money,$current_money,$change_type,
                        $in_out_type,$desc,$verify_log['admin_id'],$money_type,$verify_log['property_id'], 0);
                }
                else if($data['status'] == Constant::VERIFY_STATUS_PASSED){
                    $change_type = Constant::CHANGE_TYPE_WITHDRAWAL_PASSED;
                    $money_type = 2; //提现费用
                    $in_out_type = Constant::IN_OUT_TYPE_OUT;
                    $money = $verify_log['money'] + $verify_log['poundage'];
                    $desc = "提现成功，扣除资金.手续费:{$verify_log['poundage']}, 实际到账:{$verify_log['money']}";
                    $map['id'] = $verify_log['property_id'];
                    model('Property')->where($map)->setDec('money_lock',$money);
                    $property = model('Property')->where($map)->find();
                    $current_money = $property['money_over']+$property['money_lock'];
                    $logic = new MoneyLogic();
                    $logic->saveMoneyLog($money,$current_money,$change_type,
                        $in_out_type,$desc,$verify_log['admin_id'],$money_type,$verify_log['property_id'], 0);
                }
                $this->model->where(['id' => $ids])->update($data);
                Db::commit();
                $this->success('审核成功！');
            }catch (Exception $e){
                Db::rollback();
                $this->error('审核失败!','',$e->getMessage());
            }
        }
        return $this->view->fetch();
    }

    private function getConfigByName($name){
        $value = model('Config')->where(array('name'=>$name))->value('value');
        return $value;
    }

    public function test(){
        //审核通过 发送红包
        $utils = new WeChatSendRedPackUtils();
        $open_id = model('User')->where(array('id'=>19))->value('open_id');
        $money = 1*100;
        $act_name = '公众号发红包';
        $remark = '公众号发红包';
        $wishing = '恭喜发财！';
        $send_name = '知识黄金屋';
        $result = $utils->sendredpack($open_id,$money,$send_name,$wishing,$act_name,$remark);
        var_dump($result);
        var_dump($open_id);
    }



}